<template>
  <search v-model:options="searchOptions" @submit="searchSubmit"></search>
  <div class="task">
    <t-card :bordered="false">
      <div>
        <t-button v-auth="'monitor:job:add'" @click="onAddHander">{{ $t('menu.monitor.button.add') }}</t-button>
      </div>
      <t-table
        ref="tableRef"
        stripe
        :data="taskData"
        :columns="columns"
        row-key="id"
        :loading="tableLoading"
        :pagination="pagination"
        @change="rehandleChange"
        @page-change="onPageChange"
      />
    </t-card>
    <t-dialog v-model:visible="taskFromVisible" :footer="false" width="500px" top="20px">
      <template #header>{{ $t('menu.monitor.button.add') }}</template>
      <taskFrom ref="taskFromRef" @submit-hook="onSubmitHook"></taskFrom>
    </t-dialog>
  </div>
</template>
<script setup lang="tsx">
import {CheckIcon, CloseIcon} from 'tdesign-icons-vue-next';
import {DialogPlugin, DropdownProps, MessagePlugin} from 'tdesign-vue-next';
import {PaginationProps} from 'tdesign-vue-next/es/pagination';
import {PrimaryTableCol} from 'tdesign-vue-next/es/table/type';
import {computed, onMounted, reactive, ref} from 'vue';
import {changeStatus, deletTask, getMonitorList, runTask} from '@/api/monitor/task';
import {PageTask, Task} from '@/api/monitor/task/types';
import search, {SearchOption} from '@/components/search/index.vue';
import {ResultEnum} from '@/enums/httpEnum';
import {hasAuth, useAuth} from '@/hooks/auth';
import i18n from '@/i18n';
import {useDictStore, useSettingStore} from '@/store';
import taskFrom from './components/taskFrom.vue';
import {SYS_DICT_TYPE_JOB_GROUP, SYS_JOB_CONCURRENT} from '@/constants/dictTypes'
import TagDict from '@/components/dict/TagDict.vue';
import {useRouter} from 'vue-router';

const renderActiveContent = () => {
  return <CheckIcon/>;
};
const renderInactiveContent = () => {
  return <CloseIcon/>;
};

const router = useRouter();

// 任务组名字典数组
const groupSelectOptions = ref<DictData[]>();
const dictStore = useDictStore();

// 查询表单
const pageParams = ref<PageTask>({
  pageNumber: 1,
  pageSize: 10,
  jobName: '',
  jobGroup: undefined,
  status: undefined,
});
// 表格数据ref
const tableRef = ref();

// 分页参数
const pagination: PaginationProps = reactive({
  total: 0,
  pageEllipsisMode: 'mid',
  maxPageBtn: 5,
});
// 表格字段
const columns: Array<PrimaryTableCol<Task>> = [
  {
    colKey: 'serial-number',
    title: () => i18n.global.t('common.attribute.serialNumber'),
    width: 60,
  },
  {
    colKey: 'jobName',
    title: () => i18n.global.t('monitor.task.label.jobName'), // 任务名称
    minWidth: 100,
  },
  {
    colKey: 'jobGroup',
    title: () => i18n.global.t('monitor.task.label.jobGroup'), // 任务组名
    minWidth: 100,
    cell: (h, {col, row}) => (
      <div>
        {
          <TagDict dictType={SYS_DICT_TYPE_JOB_GROUP} value={row.jobGroup}></TagDict>
        }
      </div>
    ),
  },
  {
    colKey: 'invokeTarget',
    title: () => i18n.global.t('monitor.task.label.invokeTarget'), // 调用字符串
    minWidth: 100,
  },
  {
    colKey: 'cronExpression',
    title: () => i18n.global.t('monitor.task.label.cronExpression'), // 执行公式
    minWidth: 100,
  },
  {
    colKey: 'status',
    title: () => i18n.global.t('common.label.status'),
    minWidth: 70,
    cell: (h, {col, row}) => (
      <t-switch
        customValue={[0, 1]}
        onChange={(value: number, context: { e: MouseEvent }) => onStausChange(value, context, row)}
        size="small"
        v-model={row.status}
        disabled={!hasAuth('monitor:job:changeStatus')}
        label={[renderActiveContent, renderInactiveContent]}
      />
    ),
  },
  {
    colKey: 'operate',
    title: () => i18n.global.t('common.operate'),
    // 增、删、改、查 等操作
    cell: (h, {row}) => (
      <t-space>
        {useAuth(
          'monitor:job:edit',
          <t-link theme="primary" variant="text" hover="color" onClick={() => onEditHander(row)}>
            {i18n.global.t('common.button.edit')}
          </t-link>,
        )}
        {useAuth(
          'dict:remove',
          <t-popconfirm content={() => i18n.global.t('common.label.sureDelete')} onConfirm={() => onDeleteTask(row)}>
            <t-link variant="text" hover="color" theme="danger">
              {i18n.global.t('common.button.delete')}
            </t-link>
          </t-popconfirm>,
        )}
        {
          <t-dropdown options={tableMoreFunction(row)}>
            <t-link theme="primary" variant="text" hover="color">
              {i18n.global.t('common.button.more')}
            </t-link>
          </t-dropdown>
        }
      </t-space>
    ),
  },
];

// 分页列表数据
const taskData = ref<Task[]>([]);
const settingStore = useSettingStore();
const tableLoading = ref(false);

// 控制租户编辑表单标量
const taskFromRef = ref();
const taskFromVisible = ref(false);

// 控制租户详情表单标量
const tenantInfoFromRef = ref();
const tenantInfoFromVisible = ref(false);

/**
 * 添加定时任务适配器
 */
const onAddHander = () => {
  taskFromRef.value.initFromData();
  taskFromVisible.value = true;
};

/**
 * 编辑定时任务适配器
 */
const onEditHander = (row: Task) => {
  taskFromRef.value.initFromData(row.id);
  taskFromVisible.value = true;
};

/**
 * 删除定时任务适配器
 */
const onDeleteTask = async (row: Task) => {
  const {code} = await deletTask(row.id);
  if (code === ResultEnum.SUCCESS) {
    loadData();
  }
};

/**
 * 执行定时任务一次
 */
const onRunTask = async (row: Task) => {
  const dialog = DialogPlugin({
      header: i18n.global.t('common.label.system.Notice'),
      body: i18n.global.t('monitor.task.pl.startOnece', [row.jobName]),
      className: 't-dialog-new-class1 t-dialog-new-class2',
      style: 'color: rgba(0, 0, 0, 0.6)',
      closeOnOverlayClick: false,
      closeOnEscKeydown: false,
      onConfirm: async () => {
        await runTask(row);
        dialog.hide();
      },
      onCancel: () => dialog.hide()
    }
  )
};

/**
 * 获取任务组名字典
 */
const getSysDictTypeJobGroup = async () => {
  const sysDictTypeJobGroup = await dictStore.dictFunction(SYS_DICT_TYPE_JOB_GROUP);
  if (sysDictTypeJobGroup) {
    groupSelectOptions.value = sysDictTypeJobGroup;
  }
};

const CheckTagGroup = (row: Task) => {
  const itemIndex: number = groupSelectOptions.value.findIndex((v) => v.dictValue === row.jobGroup.toString());
  console.log(itemIndex)
  return groupSelectOptions.value[itemIndex].dictLabel;
};

/**
 * 计算更多显示内容
 */
const tableMoreFunction = (row: Task) => {
  let tableMore: DropdownProps['options'] = [];
  if (hasAuth('monitor:job:changeStatus')) {
    tableMore.push({
      content: i18n.global.t('monitor.task.button.executeOne'),
      value: 1,
      onClick: () => onRunTask(row),
    });
  }

  tableMore = tableMore.concat([
    {
      content: i18n.global.t('monitor.task.button.info'),
      value: 2,
      onClick: () => onInfoHander(row),
    },
    {
      content: i18n.global.t('monitor.task.button.logs'),
      value: 3,
      onClick: () => {
        router.push(urlConfig.detailUrl + '?jobName=' + row.jobName)
      },
    },
  ]);
  console.log('tableMore', tableMore);
  return tableMore;
};

/**
 * 租户详情表单
 * @param row 当前行数据
 */
const onInfoHander = (row: Task) => {
  taskFromRef.value.initFromData(row.id, true);
  taskFromVisible.value = true;
};

// BaseTable 中只有 page-change 事件，没有 change 事件
const rehandleChange = (changeParams: any, triggerAndData: any) => {
  console.debug('分页、排序、过滤等发生变化时会触发 change 事件：', changeParams, triggerAndData);
};

// BaseTable 中只有 page-change 事件，没有 change 事件
const onPageChange = async (pageInfo: PaginationProps) => {
  pageParams.value.pageNumber = pageInfo.current;
  pageParams.value.pageSize = pageInfo.pageSize;
  loadData();
};

import {dict} from '@/api/system/dict';
import {DictData} from '@/api/system/dict/types';
import {string} from "postcss-selector-parser";
import {SearchEnum} from '@/components/search/types';
import {urlConfig} from "./config";

/**
 * 状态切换
 * @param value
 */
const onStausChange = async (value: number, context: { e: MouseEvent }, row: Task) => {
  const body =
    value === 0
      ? i18n.global.t('monitor.task.switch.pl.status.2', {status: row.jobName})
      : i18n.global.t('monitor.task.switch.pl.status.1', {status: row.jobName});
  const dialog = DialogPlugin({
    header: i18n.global.t('common.label.system.Notice'),
    body,
    className: 't-dialog-new-class1 t-dialog-new-class2',
    style: 'color: rgba(0, 0, 0, 0.6)',
    closeOnOverlayClick: false,
    closeOnEscKeydown: false,
    confirmLoading: false,
    onConfirm: async () => {
      // confirm
      dialog.setConfirmLoading(true);
      row.status = value;
      const {result, code} = await changeStatus(row);
      if (code === ResultEnum.SUCCESS) {
        loadData();
        dialog.hide();
      }
      dialog.setConfirmLoading(false);
    },
    onCancel: () => {
      loadData();
      dialog.hide();
    },
  });
};

/**
 * 加载表格数据
 */
const loadData = async () => {
  tableLoading.value = true;
  const {code, result, message} = await getMonitorList(pageParams.value);
  if (code === ResultEnum.SUCCESS) {
    taskData.value = result.records;
    pagination.total = result.totalRow;
  }
  tableLoading.value = false;
};

/**
 * 新增/修改成功后的回调事件
 */
const onSubmitHook = () => {
  taskFromVisible.value = false;
  loadData();
};

const showBreadcrumbHeight = computed(() => {
  return settingStore.showBreadcrumb ? '46px' : '0px';
});

// 查询组件配置
const searchOptions = ref<SearchOption[]>([
  {
    name: 'roleName',
    value: '',
    label: computed(() => i18n.global.t('role.label.name')),
    placeholder: computed(() => i18n.global.t('role.label.pl.name')),
    type: SearchEnum.INPUT,
  },
  {
    name: 'roleCode',
    value: '',
    label: computed(() => i18n.global.t('role.label.code')),
    placeholder: computed(() => i18n.global.t('role.label.pl.code')),
    type: SearchEnum.INPUT,
  },
]);

onMounted(async () => {
  await getSysDictTypeJobGroup();
  loadData();
});

const searchSubmit = (params: PageTask) => {
  loadData();
};
</script>
<style scoped lang="less">
.task {
  // background: #fff;
  min-height: calc(100% - v-bind(showBreadcrumbHeight));
  display: flex;

  .t-card {
    width: 100%;
  }
}
</style>
